import ajax from '@/utils/ajax'

const type2nameMap = {
  // radio: 'SingleChoose',
  // checkbox: 'MultiChoose',
  // blank: 'Blank'
}
const appId = 'wxf2ab3d711f0dfe27'
const companyId = 8
const handleList = (list) => {
  list.forEach(item => {
    item.componentName = type2nameMap[item.questionType] || item.questionType
    try {
      item.questionContent = JSON.parse(item.questionContent)
    } catch (e) {
      console.error('json转换出错了', e)
    }
  })
  return list
}

/**
* 生成唯一的uuid值传回后台，genUUID(12, 16)
*/
export const genUUID = (len, radix) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []; let i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  } else {
    // rfc4122, version 4 form
    let r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

export const getServerTime = async (id) => {
  const resData = await ajax.get('/api/v1/fe/survey/getServerTime.do', {
    params: {
      id
    }
  })
  const res = resData.result

  return res
}

export const saveExam = async (data) => {
  const resData = await ajax.post('/api/v1/fe/survey/saveAnswer.do', {
    data
  })
  const res = resData.result

  return res
}
export const getQuestions = async () => {
  try {
    const resData = await ajax.get('/survey/minimall/question/get-list-by-appid.do', {
      params: {
        appId,
        companyId
      }
    })
    const res = resData.result

    res.list = handleList(res.list)
    return res.list
  } catch (e) {
    // console.log('e', e)
  }
}

export const submit = async (data) => {
  const res = await ajax.post('/api/v1/fe/survey/submit.do', {
    data
  })
  return res
}

export const getAnswer = async (id) => {
  const res = await ajax.get('/api/v1/fe/survey/getAnswer.do', {
    params: {
      id
    }
  })

  return res.result
}

export const getSurvey = async (id) => {
  const res = await ajax.get('/api/v1/fe/survey/getSurvey.do', {
    params: {
      id
    }
  })

  return res.result
}

export const sendMessage = async (id) => {
  const res = await ajax.get('/api/v1/fe/survey/sendMessage.do', {
    params: {
      id
    }
  })

  return res
}

export const submitRemark = async (data) => {
  const res = await ajax.post('/api/v1/fe/survey/submitRemark.do', {
    data
  })
  return res
}
